#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using Net.Helper;
using UnityEditorInternal;

public class ExtraSolutionTools : EditorWindow
{
    private Vector2 scrollPosition;
    private ReorderableList _reorderableList;
    private List<string> _projectPaths = new();

    [MenuItem("GameDesigner/Tools/ExtraSolution")]
    private static void Init()
    {
        var window = GetWindow<ExtraSolutionTools>();
        window.titleContent = new GUIContent("项目解决方案工具", EditorGUIUtility.IconContent("d_FolderFavorite Icon").image);
        window.Show();
    }

    private void OnEnable()
    {
        _projectPaths = PersistHelper.Deserialize("ExtraSolution.json", new List<string>(), true);
        _reorderableList = new ReorderableList(_projectPaths, typeof(List<string>), true, true, false, true)
        {
            drawHeaderCallback = DrawHeaderCallback
        };
    }

    private static void DrawHeaderCallback(Rect rect)
    {
        EditorGUI.LabelField(rect, "C#项目列表:");
    }

    private void OnGUI()
    {
        EditorGUI.BeginChangeCheck();
        scrollPosition = GUILayout.BeginScrollView(scrollPosition, false, true);
        _reorderableList.DoLayoutList();
        GUILayout.EndScrollView();
        if (GUILayout.Button("添加项目文件"))
        {
            var path = EditorUtility.OpenFilePanel("Select .csproj", Application.dataPath, "csproj");
            if (!string.IsNullOrEmpty(path))
            {
                var relativePath = PathHelper.GetRelativePath(Application.dataPath, path);
                _projectPaths.Add(relativePath);
            }
        }
        if (GUILayout.Button("更新解决方案"))
        {
            AssetDatabase.Refresh();
            Unity.CodeEditor.CodeEditor.Editor.CurrentCodeEditor.SyncAll();
        }
        if (EditorGUI.EndChangeCheck())
            PersistHelper.Serialize(_projectPaths, "ExtraSolution.json");
    }

    public static string ChangeSlnSolution(string path, string content)
    {
        var projectPaths = PersistHelper.Deserialize("ExtraSolution.json", new List<string>(), true);
        var endGlobalIndex = content.IndexOf("Global");
        if (endGlobalIndex < 0 || projectPaths.Count <= 0)
            return content;
        var projectEntries = "";
        var configEntries = "";
        foreach (var csprojPath in projectPaths)
        {
            var projectName = Path.GetFileNameWithoutExtension(csprojPath);
            if (content.Contains(projectName))
                continue;
            var crc = projectName.CRCU32();
            var guidBytes = new byte[16];
            Buffer.BlockCopy(BitConverter.GetBytes(crc), 0, guidBytes, 0, 4);
            for (var i = 4; i < 16; i++)
                guidBytes[i] = (byte)(crc >> (i % 4) * 8);
            var projectGuid = new Guid(guidBytes).ToString().ToLower();
            projectEntries += $@"Project(""{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}"") = ""{projectName}"", ""{csprojPath}"", ""{{{projectGuid}}}""
EndProject
";
            configEntries += $@"
		{{{projectGuid}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
        {{{projectGuid}}}.Debug|Any CPU.Build.0 = Debug|Any CPU
        {{{projectGuid}}}.Release|Any CPU.ActiveCfg = Release|Any CPU
        {{{projectGuid}}}.Release|Any CPU.Build.0 = Release|Any CPU";
        }
        if (string.IsNullOrEmpty(projectEntries))
            return content;
        content = content.Insert(endGlobalIndex, projectEntries);
        if (content.Contains("GlobalSection(ProjectConfigurationPlatforms)"))
        {
            content = content.Replace(
                "GlobalSection(ProjectConfigurationPlatforms) = postSolution",
                $"GlobalSection(ProjectConfigurationPlatforms) = postSolution{configEntries}"
            );
        }
        return content;
    }
}
#endif